package com.whmnx.chitchat.ui.book;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.RecyclerView;

import com.classic.adapter.CommonRecyclerAdapter;
import com.orhanobut.logger.Logger;
import com.tencent.openqq.protocol.imsdk.msg;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.adapter.GroupMeberAdpter;
import com.whmnx.chitchat.base.BaseActivity;
import com.whmnx.chitchat.bean.BaseBean;
import com.whmnx.chitchat.bean.GroupBean;
import com.whmnx.chitchat.bean.GroupDatailBean;
import com.whmnx.chitchat.bean.ImgResultBean;
import com.whmnx.chitchat.bean.LoginBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.LoginActivity;
import com.whmnx.chitchat.ui.chat.AddGroupActivity;
import com.whmnx.chitchat.ui.chat.ChatActivity;
import com.whmnx.chitchat.ui.chat.FriendInfoActivity;
import com.whmnx.chitchat.ui.chat.SearchActivity;
import com.whmnx.chitchat.ui.my.ChangeInfoActivity;
import com.whmnx.chitchat.ui.my.MyInfoActivity;
import com.whmnx.chitchat.utils.ImageUtil;
import com.whmnx.chitchat.utils.PhotoUtil;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;
import com.whmnx.chitchat.view.CommonDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author : huang
 * date   : 2020/8/5 0005 19:19
 * version: 1.0
 *
 * @author Administrator
 */
public class GroupMeberActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.rv_group)
    RecyclerView rvGroup;
    @BindView(R.id.tv_group_name)
    TextView tvGroupName;
    @BindView(R.id.tv_group_nick)
    TextView tvGroupNick;
    @BindView(R.id.tv_announcement)
    TextView tvAnnouncement;
    @BindView(R.id.tv_group_out)
    TextView tvGoupOut;
    @BindView(R.id.iv_user)
    CircleImageView ivUser;
    private int group_type;
    private String group_ID,UserNick;

    private Dialog dialogHead;
    private Uri imageUri;
    private Uri cropImageUri;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    /* 请求识别码 */
    public static final int CODE_GALLERY_REQUEST = 0xa0;
    public static final int CODE_CAMERA_REQUEST = 0xa1;
    public static final int CODE_RESULT_REQUEST = 0xa2;

    public static int OUTPUT_X = 480;
    public static int OUTPUT_Y = 480;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.group_meber_activity);
        setTitle("聊天信息");
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.ADDFRIENDS)) {
                loadData();
            }
        }
    }

    @Override
    protected void loadData() {
        rvGroup.setItemAnimator(new DefaultItemAnimator());
        GroupMeberAdpter groupAdpter = new GroupMeberAdpter(this);
        rvGroup.setAdapter(groupAdpter);

        Map<String, Object> params = new HashMap<>();
        params.put("GroupID", getIntent().getStringExtra("Group_ID"));
        HttpClient.get(GroupMeberActivity.this, Constants.GETGROUPMENBERSBYGROUPID, params, new CallBack<GroupDatailBean>() {
            @Override
            public void onSuccess(GroupDatailBean result) {
                setTitle("聊天信息(" + result.getGroupMembersList().size() + ")");
                if (result.getGroupMembersList().size() > 0) {
                    GroupDatailBean.GroupMembersListBean groupBean = new GroupDatailBean.GroupMembersListBean();
                    groupBean.setUserNick("");
                    result.getGroupMembersList().add(groupBean);
                    groupAdpter.addAll(result.getGroupMembersList());
                    tvGroupName.setText(result.getGroup().getGroup_Name());
                    if (TextUtils.isEmpty(result.getGroup().getGroup_Notice())){
                        tvAnnouncement.setVisibility(View.GONE);
                    }else {
                        tvAnnouncement.setText(result.getGroup().getGroup_Notice());
                    }
                    ImageUtil.setImage(ivUser, result.getGroup().getGroup_Img());

                    String userId = SPUtil.getString(Constants.USERID);
                    group_ID = result.getGroup().getGroup_ID();
                //    group_ID = result.getGroup().get();
                    for (GroupDatailBean.GroupMembersListBean bean : result.getGroupMembersList()) {  //6ac6a653-3f4c-4043-a592-e5ec3c446ec8
                        if (bean.getGroupMembers_UserID().equals(userId)) {
                            group_type = bean.getGroupMembers_Type();
                            UserNick = bean.getUserNick();
                            tvGroupNick.setText(UserNick);
                            break;
                        }
                    }
                    //1是 管量员，2 是群主
                    if (group_type != 0) {
                        tvGoupOut.setText("删除群聊");
                    }
                }
            }
        });

        groupAdpter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder, View view, int i) {
                if (TextUtils.isEmpty(groupAdpter.getItem(i).getUserNick())){
                    startActivity(new Intent(GroupMeberActivity.this, AddGroupActivity.class).putExtra("type", 2)
                            .putExtra("group_id", group_ID));
                }else {
                    if (TextUtils.isEmpty(groupAdpter.getItem(i).getGroupMembers_UserID())) return;
                    Intent intent = new Intent();
                    intent.putExtra("userId", groupAdpter.getItem(i).getGroupMembers_UserID());
                    intent.putExtra("type",2);
                    intent.setClass(GroupMeberActivity.this, FriendInfoActivity.class);
                     startActivity(intent);
                }
            }
        });
    }

    @OnClick({R.id.rl_group_name, R.id.rl_group_nick, R.id.rl_announcement, R.id.tv_group_out,R.id.ll_photo,R.id.tv_del,R.id.rl_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_group_name:
                Intent intentCamera = new Intent();
                intentCamera.setClass(this, ChangeInfoActivity.class);
                intentCamera.putExtra("type", 2);
                intentCamera.putExtra("GroupID", group_ID);
                startActivityForResult(intentCamera, 100);
                break;
            case R.id.rl_group_nick:
                if (group_type != 0) {

                }
                Intent intent = new Intent();
                intent.setClass(this, ChangeInfoActivity.class);
                intent.putExtra("type", 3);
                intent.putExtra("GroupID", group_ID);
                startActivityForResult(intent, 200);
                break;
            case R.id.ll_photo:
                showHeadDialog();
                if (group_type != 0) {
                }
                break;
            case R.id.rl_search:
                Intent intent2 = new Intent(UItils.getContext(), SearchActivity.class);
                intent2.putExtra(TUIKitConstants.GroupType.GROUP, true);
                intent2.putExtra("toUserId", group_ID);
                startActivity(intent2);
                break;
            case R.id.tv_del:
                String s2 = "确定清空群聊天记录吗?";
                new CommonDialog(this, R.style.dialog, s2, (dialog, confirm) -> {
                    if (confirm) {
                        delGroupMsg();
                    }
                    dialog.dismiss();
                }).show();

                break;
            case R.id.rl_announcement:
                if (group_type != 0) {
                    Intent nickIntent = new Intent();
                    nickIntent.setClass(this, ChangeInfoActivity.class);
                    nickIntent.putExtra("type", 1);
                    nickIntent.putExtra("group_id", group_ID);
                    startActivityForResult(nickIntent, 300);
                }else {
                    UItils.showToastSafe("不是群管理员,暂不能发布");
                }
                break;
            case R.id.tv_group_out:
                Map<String, Object> params = new HashMap<>();
                params.put("GroupID", getIntent().getStringExtra("Group_ID"));
                params.put("UserID", SPUtil.getString(Constants.USERID));
                HttpClient.get(GroupMeberActivity.this, Constants.GETDELETEGROUPANDCHATRECORD, params, new CallBack<GroupDatailBean>() {
                    @Override
                    public void onSuccess(GroupDatailBean result) {
                        //  UItils.showToastSafe("删除群组成功");
                        MessageEvent messageEvent = new MessageEvent();
                        messageEvent.setMessageKey(EventConstants.DEL);
                        EventBus.getDefault().post(messageEvent);
                        finish();
                    }
                });
                break;
            default:
        }
    }

    private void delGroupMsg() {
        Map<String, Object> params = new HashMap<>();
        params.put("UserID", SPUtil.getString(Constants.USERID));
       // params.put("ChatRecordIDs", item.getChatRecordID());
      //  int type = item.getChatRecordRecordType() == 0 ? 0 : 1;
        params.put("RecordType", 0 + "");
        params.put("GroupID", group_ID);
        HttpClient.get(this, Constants.GETDELETECHATRECORD, params, new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                UItils.showToastSafe("清空群消息成功");
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.DELMSG);
                EventBus.getDefault().post(messageEvent);
            }
        });
    }


    private void showHeadDialog() {
        dialogHead = new Dialog(this, R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_head_portrait2, null);
        view.findViewById(R.id.dialog_shoot).setOnClickListener(this);
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(this);
        view.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        //显示对话框//设置Dialog从窗体底部弹出
        dialogHead.show();
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置Dialog距离底部的距离
        lp.y = 20;
        //将属性设置给窗体
        window.setAttributes(lp);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //拍摄
            case R.id.dialog_shoot:
                imageUri = Uri.fromFile(fileUri);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(this, "com.whmnx.chitchat.FileProvider", fileUri);
                }
                PhotoUtil.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                //   photoUtils.takePicture(MyUserInfoActivity.this);
                dialogHead.dismiss();
                break;
            //相册
            case R.id.dialog_photo_album:
                PhotoUtil.openPic(this, CODE_GALLERY_REQUEST);
                // photoUtils.takePicture(MyUserInfoActivity.this);
                //  photoUtils.selectPicture(MyUserInfoActivity.this);
                dialogHead.dismiss();
                break;
            //取消
            case R.id.dialog_cancel:
                dialogHead.dismiss();
                break;
            default:
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    tvGroupName.setText(data.getStringExtra("name"));
                    MessageEvent messageEvent = new MessageEvent();
                    messageEvent.setMessageKey(EventConstants.GROUP);
                    EventBus.getDefault().post(messageEvent);
                    break;
                case 200:
                    tvGroupNick.setText(data.getStringExtra("name"));
                    break;
                case 300:
                    tvAnnouncement.setText(data.getStringExtra("name"));
                    MessageEvent messageEvent2 = new MessageEvent();
                    messageEvent2.setMessageKey(EventConstants.DELMSG);
                    EventBus.getDefault().post(messageEvent2);
                    break;
                case CODE_CAMERA_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtil.cropImageUri(this, imageUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST:
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(PhotoUtil.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.whmnx.chitchat.FileProvider", new File(newUri.getPath()));
                    }
                    PhotoUtil.cropImageUri(this, newUri, cropImageUri, 1, 1, OUTPUT_X, OUTPUT_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_RESULT_REQUEST:
                    // Bitmap bitmap = BitmapFactory.decodeFile(cropImageUri.getPath());
                    Bitmap bitmap = PhotoUtil.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {
                        //  flag = true;
                        ivUser.setImageBitmap(bitmap);
                        String url = Constants.UPLOADHEADIMG + "?foldername=HeadImg";
                        List<File> files = new ArrayList<>();
                        files.add(fileCropUri);
                        HttpClient.postImg(this, url, files, new CallBack<List<ImgResultBean>>() {
                            @Override
                            public void onSuccess(List<ImgResultBean> baseBean) {
                                String url = (String) baseBean.get(0).fullPath;
                                Map<String, Object> params = new HashMap<>();
                                params.put("UserID",SPUtil.getString(Constants.USERID));
                                params.put("GroupID",group_ID);
                                params.put("Img",url);
                                HttpClient.get(GroupMeberActivity.this, Constants.GETUPDATEGROUPIMG, params,new CallBack<BaseBean>() {
                                    @Override
                                    public void onSuccess(BaseBean result) {
                                          //  String url = (String) baseBean.get(0).fullPath;
                                            Logger.i("hhh",result);
                                          // SPUtil.put(Constants.HEAD_IMG, url);
                                            ImageUtil.setImage(ivUser, url);
                                            MessageEvent messageEvent = new MessageEvent();
                                            messageEvent.setMessageKey(EventConstants.GROUP);
                                            EventBus.getDefault().post(messageEvent);
                                    }
                                });
                            }
                        });
                    }
                    break;
                default:
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
